package com.fashion.web.actions.management.news;

import com.fashion.exceptions.KindEditorException;
import com.fashion.utils.StringUtils;
import com.fashion.utils.kindeditor.NameComparator;
import com.fashion.utils.kindeditor.SizeComparator;
import com.fashion.utils.kindeditor.TypeComparator;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: gnyk
 * Date: 13-3-28
 */
@Scope("prototype")
@Controller
@ParentPackage("json-default")
@Namespace("/ke")
public class KindEditorAction extends ActionSupport implements ServletRequestAware {
    private static final Logger logger = Logger.getLogger(KindEditorAction.class);
    private static final String userFilesRoot = "attach";

    //parameters for upload
    private String jsonResult;
    private HttpServletRequest request;
    private File imgFile;
    private String dir;
    private String savePath;
    //文件保存目录URL
    private String saveUrl = "/" + userFilesRoot + "/";
    //定义允许上传的文件扩展名
    private static HashMap<String, String> extMap = new HashMap<String, String>();
    private Map<String, Object> uploadFile;

    //parameters for browse pictures
    //根目录路径，可以指定绝对路径，比如 /var/www/attached/
    private String rootPath;
    //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
    private String rootUrl;
    //图片扩展名
    private String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
    private Map<String, Object> fileListBrowser;

    static {
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
    }

    //最大文件大小
    private long maxSize = 1000000;

    @Action(value = "upload", results = {@Result(name = SUCCESS, type = "json", params = {
            "root", "uploadFile"})})
    public String upload() throws Exception {
        uploadFile = new HashMap<String, Object>();
        savePath = ServletActionContext.getServletContext().getRealPath("/") + userFilesRoot + "/";
        try {
            initFolders();
            saveFiles();
        } catch (FileUploadException e) {
            generateErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "browsePictures", results = {@Result(name = SUCCESS, type = "json", params = {
            "root", "fileListBrowser"})})
    public String browsePictures() throws Exception {
        rootPath = ServletActionContext.getServletContext().getRealPath("/") + userFilesRoot + "/";
        rootUrl = request.getContextPath() + "/" + userFilesRoot + "/";

        String dirName = request.getParameter("dir");
        if (dirName != null) {
            if (!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)) {
                logger.error("Invalid Directory name.");
                return SUCCESS;
            }
            rootPath += dirName + "/";
            rootUrl += dirName + "/";
            File saveDirFile = new File(rootPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
        }
//根据path参数，设置各路径和URL
        String path = request.getParameter("path") != null ? request.getParameter("path") : "";
        String currentPath = rootPath + path;
        String currentUrl = rootUrl + path;
        String currentDirPath = path;
        String moveUpDirPath = "";
        if (!"".equals(path)) {
            String str = currentDirPath.substring(0, currentDirPath.length() - 1);
            moveUpDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
        }

//排序形式，name or size or type
        String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

//不允许使用..移动到上一级目录
        if (path.indexOf("..") >= 0) {
            logger.error("Access is not allowed.");
            return SUCCESS;
        }
//最后一个字符不是/
        if (!"".equals(path) && !path.endsWith("/")) {
            logger.error("Parameter is not valid.");
            return SUCCESS;
        }
//目录不存在或不是目录
        File currentPathFile = new File(currentPath);
        if (!currentPathFile.isDirectory()) {
            logger.error("Directory does not exist.");
            return SUCCESS;
        }

//遍历目录取的文件信息
        List<Hashtable> fileList = new ArrayList<Hashtable>();
        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }

        if ("size".equals(order)) {
            Collections.sort(fileList, new SizeComparator());
        } else if ("type".equals(order)) {
            Collections.sort(fileList, new TypeComparator());
        } else {
            Collections.sort(fileList, new NameComparator());
        }

        //  JSONObject result = new JSONObject();
        fileListBrowser = new HashMap<String, Object>();
        fileListBrowser.put("moveup_dir_path", moveUpDirPath);
        fileListBrowser.put("current_dir_path", currentDirPath);
        fileListBrowser.put("current_url", currentUrl);
        fileListBrowser.put("total_count", fileList.size());
        fileListBrowser.put("file_list", fileList);

        return SUCCESS;
    }

    protected void saveFiles() throws FileUploadException {
        String[] fileNames = ((MultiPartRequestWrapper) request).getFileNames("imgFile");

        if (fileNames.length < 1) {
            throw new KindEditorException("未找到上传文件。");
        }

        String fileName = fileNames[0];
        long fileSize = imgFile.length();
        if (fileSize > maxSize) {
            throw new KindEditorException("上传文件大小超过限制。");
        }
        //检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get(dir).split(",")).contains(fileExt)) {
            throw new KindEditorException("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dir) + "格式。");
        }

        String newFileName = StringUtils.createTimeStamp() + "_" + new Random().nextInt(1000) + "." + fileExt;
        try {
            FileUtils.copyFile(imgFile, new File(savePath, newFileName));
        } catch (Exception e) {
            throw new KindEditorException("上传文件失败。");
        }

        uploadFile.put("error", 0);
        uploadFile.put("url", saveUrl + newFileName);
    }

    protected void initFolders() {
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new KindEditorException("请选择文件。");
        }

        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            logger.error("上传目录不存在。");
            if (!uploadDir.mkdir()) {
                throw new KindEditorException("不能创建上传目录");
            }
        }

        if (!uploadDir.canWrite()) {
            throw new KindEditorException("上传目录没有写权限。");
        }

        if (!extMap.containsKey(dir)) {
            throw new KindEditorException("目录名不正确。");
        }

        savePath += dir + "/";
        saveUrl += dir + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }

        String monthStamp = StringUtils.generateNameByYearAndMonth();

        savePath += monthStamp + "/";
        saveUrl += monthStamp + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
    }

    protected void generateErrorMessage(String message) {
        uploadFile.put("error", 1);
        uploadFile.put("message", message);
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    public File getImgFile() {
        return imgFile;
    }

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

    public Map<String, Object> getFileListBrowser() {
        return fileListBrowser;
    }

    public void setFileListBrowser(Map<String, Object> fileListBrowser) {
        this.fileListBrowser = fileListBrowser;
    }

    public Map<String, Object> getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(Map<String, Object> uploadFile) {
        this.uploadFile = uploadFile;
    }
}
